// 云对象教程: https://uniapp.dcloud.net.cn/uniCloud/cloud-obj
// jsdoc语法提示教程：https://ask.dcloud.net.cn/docs/#//ask.dcloud.net.cn/article/129

const db = uniCloud.database()
const users = db.collection('sunny-users')
const dbcmd = db.command
module.exports = {
	_before: function(data) { // 通用预处理器
		console.log('预处理data', data)
	},
	/**
	 * method1方法描述
	 * @param {string} param1 参数1描述
	 * @returns {object} 返回值描述
	 */

	login: async function(item) {
		let dbUser = await users.where({
			name: item.username,
			delFlag: db.command.neq(1) // 排除已删除的用户
		}).get()
		if (!dbUser || dbUser.data.length === 0) {
			return {
				code: 200,
				resultCode: 1,
				errorMsg: '用户不存在'
			}
		}
		let user = dbUser.data[0]
		if (user.password != item.password) {
			return {
				code: 200,
				resultCode: 1,
				errorMsg: '用户名密码错误'
			}
		}
		return {
			code: 200,
			resultCode: 0,
			msg: '登录成功',
			data: user
		}
	},

	/**
	 * 用户注册接口
	 * @param {object} userInfo 用户信息
	 * @param {string} userInfo.username 用户名
	 * @param {string} userInfo.password 密码
	 * @param {string} userInfo.role 用户角色
	 * @returns {object} 注册结果
	 */
	register: async function(userInfo) {
		// 检查用户名是否已存在
		const existUser = await users.where({
			name: userInfo.username
		}).get()

		if (existUser.data.length > 0) {
			return {
				code: 200,
				resultCode: 1,
				errorMsg: '用户名已存在'
			}
		}

		// 创建新用户
		const result = await users.add({
			name: userInfo.username,
			password: userInfo.password,
			role: userInfo.role || 'user', // 默认角色为user
			create_time: new Date(),
			update_time: new Date(),
			status: 0 // 0表示正常状态
		})

		if (result.id) {
			return {
				code: 200,
				resultCode: 0,
				msg: '注册成功',
				data: {
					userId: result.id
				}
			}
		} else {
			return {
				code: 200,
				resultCode: 1,
				errorMsg: '注册失败，请重试'
			}
		}
	},


	async getMemberList(params) {
		const {
			page = 1, pageSize = 20
		} = params;
		const db = uniCloud.database();
		const collection = db.collection('sunny-users');

		const res = await collection
			.where({
				role: db.command.in([3, 4, 5, 6]), // 只返回团队角色
				delFlag: db.command.neq(1) // 排除已逻辑删除的成员
			})
			.orderBy('createTime', 'desc')
			.skip((page - 1) * pageSize)
			.limit(pageSize)
			.get();


		return {
			code: 200,
			resultCode: 0,
			data: res.data,
			message: '获取成功'
		};
	},

	// 添加成员
	async addMember(params) {
		const {
			name,
			phone,
			role,
			agency,
			password,
			status,
			nickName
		} = params;
		const db = uniCloud.database();
		const collection = db.collection('sunny-users');

		// 检查手机号是否已存在
		const existing = await collection.where({
			phone
		}).get();
		if (existing.data.length > 0) {
			return {
				code: -1,
				resultCode: -1,
				message: '该手机号已存在'
			};
		}

		const memberData = {
			name,
			nickName,
			phone,
			role,
			agency: role === 4 ? agency : '', // 只有中介角色才保存中介公司
			password, // 实际使用时应该加密存储
			status: status || 1,
			createTime: Date.now(),
			updateTime: Date.now()
		};

		const res = await collection.add(memberData);

		return {
			code: 200,
			resultCode: 0,
			data: res,
			message: '添加成功'
		};
	},

	// 更新成员
	async updateMember(params) {
		const {
			_id,
			name,
			phone,
			role,
			agency,
			password,
			status
		} = params;
		const db = uniCloud.database();
		const collection = db.collection('sunny-users');

		const updateData = {
			name,
			phone,
			role,
			agency: role === 4 ? agency : '',
			status,
			updateTime: Date.now()
		};

		// 如果传了密码才更新密码
		if (password) {
			updateData.password = password;
		}

		const res = await collection.doc(_id).update(updateData);

		return {
			code: 0,
			data: res,
			message: '更新成功'
		};
	},

	// 删除成员(逻辑删除)
	async deleteMember(params) {
		const {
			id
		} = params;
		const db = uniCloud.database();
		const collection = db.collection('sunny-users');

		const res = await collection.doc(id).update({
			delFlag: 1,
			updateTime: Date.now()
		});

		return {
			code: 0,
			data: res,
			message: '删除成功'
		};
	},

	// 修改密码
	async changePassword(params) {
		const {
			userId,
			oldPassword,
			newPassword
		} = params;
		const db = uniCloud.database();
		const collection = db.collection('sunny-users');

		// 验证旧密码
		const user = await collection.doc(userId).get();
		if (!user.data || user.data.length === 0) {
			return {
				code: 404,
				resultCode: 1,
				errorMsg: '用户不存在'
			};
		}

		if (user.data[0].password !== oldPassword) {
			return {
				code: 401,
				resultCode: 1,
				errorMsg: '旧密码不正确'
			};
		}

		// 更新密码
		const res = await collection.doc(userId).update({
			password: newPassword,
			updateTime: Date.now()
		});

		return {
			code: 200,
			resultCode: 0,
			message: '密码修改成功'
		};
	},

	// 切换用户状态
	async toggleUserStatus(params) {
		const {
			userId
		} = params;
		const db = uniCloud.database();
		const collection = db.collection('sunny-users');

		// 获取当前状态
		const user = await collection.doc(userId).get();
		if (!user.data || user.data.length === 0) {
			return {
				code: 404,
				resultCode: 1,
				errorMsg: '用户不存在'
			};
		}

		const currentStatus = user.data[0].status;
		const newStatus = currentStatus === 1 ? 0 : 1; // 切换状态

		// 更新状态
		const res = await collection.doc(userId).update({
			status: newStatus,
			updateTime: Date.now()
		});

		return {
			code: 200,
			resultCode: 0,
			message: newStatus === 1 ? '用户已启用' : '用户已禁用',
			data: {
				newStatus
			}
		};
	},
	async toggleUserOnline(params) {
		const {
			userId
		} = params;
		const db = uniCloud.database();
		const collection = db.collection('sunny-users');
	
		// 获取当前状态
		const user = await collection.doc(userId).get();
		if (!user.data || user.data.length === 0) {
			return {
				code: 404,
				resultCode: 1,
				errorMsg: '用户不存在'
			};
		}
	
		const currentStatus = user.data[0].isOnline;
		const newStatus = currentStatus === 1 ? 0 : 1; // 切换状态
	
		// 更新状态
		const res = await collection.doc(userId).update({
			isOnline: newStatus,
			updateTime: Date.now()
		});
	
		return {
			code: 200,
			resultCode: 0,
			message: newStatus === 1 ? '用户已上线' : '用户已下线',
			data: {
				newStatus
			}
		};
	},


	async getConsultantList() {
		const db = uniCloud.database();
		const collection = db.collection('sunny-users');

		const res = await collection
			.where({
				role: 3, // 置业顾问角色
				status: 1,
				isOnline:1// 启用状态
			})
			.field({
			        _id: true,
			        name: true,
			        phone: true,
			        isOnline: true,
			        nickName: true
			    })
			.orderBy('createTime', 'desc')
			.get();
		
		console.log(res)
		
		return {
			code: 200,
			resultCode:0,
			data: res.data,
			message: '获取成功'
		};
	}
}